﻿/**
    xie yun define the object to hold all data source in application
*/

ePOS.common.util.DataSet = function(cfg){
		if(cfg.url != undefined){
			cfg.root = 'rows'
		}
		Ext.apply(this,cfg,{});
	};
Ext.apply(ePOS.common.util.DataSet.prototype,{
    createBlankRecord:function(){
		var ds_record = Ext.data.Record.create(this.dt.fields);
		return new ds_record(new this.dt.DataObj());
	},
    addRecord:function(rec,post_action){
		var act = post_action ? post_action:{};
		var ds = this;
		Ext.Ajax.request({
            url:this.addupdateUrl,
            method:"POST",
            params:{
            	action:'add',
                rec:Ext.util.JSON.encode(rec)
                },
            success:function(response,parameter){
            	rec.id = response.result.msg;
            	ds.getStore().add(rec);
				var scope = act.scope? act.scope:this;
				if(act.success){
					act.success.call(scope);
				}
            },
            failure:function(res,para){
                var scope = act.scope? act.scope:this;
            	if(act.failure){
            		act.failure.call(scope);
				}
            }
        });
		this.getStore().add(rec);
	},
    updateRecord:function(rec,new_data,post_action){ //the rec should be the instance of Record
		var ds = this;
		var act = post_action ? post_action:{};
		rec.beginEdit();
		Ext.apply(rec.data,new_data);	//Assume no change on key
		Ext.Ajax.request({
            url:this.addupdateUrl,
            method:"POST",
            params:{
            	action:'update',
                rec:Ext.util.JSON.encode(rec.data)
                },
            success:function(response,parameter){
            	rec.commit();
            	var scope = act.scope? act.scope:this;
				if(act.success){
					act.success.call(scope);
				}
           	},
            failure:function(res,para){
                rec.cancelEdit();
                var scope = act.scope? act.scope:this;
            	if(act.failure){
            		act.failure.call(scope);
				}
            }
        });
	},
    deleteRecord:function(rec){
		if(this.deleteUrl){
			Ext.Ajax.request({
                url:this.deleteUrl,
                params:{rec:Ext.util.JSON.encode(rec.data)},		//todo: rec.id应该与数据模版定义相关
                success:function(){
                    this.getStore().remove(rec);
                },
                failure:function(){
                    Ext.Msg.show('错误','删除失败');
                },
                scope:this
            });
        }
	}
    
});

